<template>
  <div class="goods_details">
    <el-container class="base_details_container">
      <BackTitleView :title="title" />
      <el-main>
        <el-tabs
          v-model="activeName"
          type="border-card"
          class="base_details_tabs"
        >
          <el-tab-pane name="basic">
            <template #label>
              <el-badge>
                <span>基本信息</span>
              </el-badge>
            </template>
            <div class="content">
              <div class="base_details_title">基本信息</div>
              <div class="base_details_content_second">
                <el-form
                  ref="basicFormRef"
                  :model="basicForm"
                  :disabled="readOnly"
                  :rules="basicRules"
                  label-width="100px"
                  class="base_details_form"
                >
                  <el-form-item label="商品分类" prop="categoryCode">
                    <el-select
                      v-model="basicForm.categoryCode"
                      placeholder="请选择"
                    >
                      <el-option
                        v-for="(item, index) in typeOptions"
                        :key="index"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="发货方式" prop="limitDeliveryType">
                    <el-radio-group v-model="basicForm.limitDeliveryType">
                      <el-radio
                        v-for="(item, index) in deliverOptions"
                        :key="index"
                        :label="item.value"
                      >
                        {{ item.label }}
                      </el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item label="商品名称" prop="productName">
                    <el-input
                      v-model="basicForm.productName"
                      placeholder="请输入"
                    />
                  </el-form-item>
                  <!-- <el-form-item label="归属基地" prop="shopCode">
                    <el-select v-model="basicForm.shopCode" placeholder="请选择">
                      <el-option v-for="(item, index) in baseOptions" :key="index" :label="item.label"
                        :value="item.value" />
                    </el-select>
                  </el-form-item> -->
                  <el-form-item label="商品封面" prop="picList">
                    <UploadPicture
                      v-model="basicForm.picList"
                      :limit="10"
                      :imgSize="$.describeImgSize()"
                      :fileSize="$.imgFileSize()"
                      :disabled="readOnly"
                    />
                  </el-form-item>
                  <el-form-item label="商品简介" prop="descList">
                    <UploadPicture
                      v-model="basicForm.descList"
                      :limit="50"
                      :fileSize="$.imgFileSize()"
                      :disabled="readOnly"
                    />
                  </el-form-item>
                  <el-form-item label="商品单位" prop="sellUnit">
                    <el-radio-group v-model="basicForm.sellUnit">
                      <el-radio
                        v-for="(item, index) in unitOptions"
                        :key="index"
                        :label="item"
                      />
                    </el-radio-group>
                    <el-input
                      class="unit_input"
                      v-model="otherUnit"
                      placeholder="单位"
                    />
                  </el-form-item>
                  <el-form-item
                    v-if="basicForm.limitDeliveryType != '1045003'"
                    label="邮费模板"
                    prop="postageTempleteCode"
                  >
                    <el-select
                      v-model="basicForm.postageTempleteCode"
                      placeholder="请选择"
                    >
                      <el-option
                        v-for="item in postageOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                  <el-form-item
                    v-if="basicForm.limitDeliveryType != '1045002'"
                    label="可选自提点"
                    prop="stationIds"
                  >
                    <el-select
                      v-model="basicForm.stationIds"
                      multiple
                      placeholder="请选择"
                    >
                      <el-option
                        v-for="item in stationOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="产品标签">
                    <el-radio-group v-model="basicForm.tags">
                      <el-radio
                        v-for="(item, index) in labelOptions"
                        :key="index"
                        :label="item.value"
                      >
                        {{ item.label }}
                      </el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item label="限购数量">
                    <el-input
                      v-model="basicForm.maxBuy"
                      type="number"
                      onkeyup="value=value.replace(/^(0+)|[^\d]+/g,'')"
                      placeholder="请输入（不输入则表示不限购）"
                    />
                  </el-form-item>
                  <el-form-item label="起购数量" prop="minBuy">
                    <el-input
                      v-model.number="basicForm.minBuy"
                      type="number"
                      onkeyup="value=value.replace(/^(0+)|[^\d]+/g,'')"
                      placeholder="请输入"
                    />
                  </el-form-item>
                </el-form>
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane name="spec">
            <template #label>
              <el-badge>
                <span>规格设置</span>
              </el-badge>
            </template>
            <div class="content">
              <div class="base_details_title">规格设置<b></b></div>
              <div class="base_details_content_second">
                <GoodsSpecs
                  ref="goodsSpecs"
                  :specs="specsOptions"
                  :data="specsData"
                  :readOnly="readOnly"
                  :isModify="isModify"
                />
              </div>
              <div class="base_details_title_button">
                <div class="tb_title">SKU管理<b></b></div>
                <el-button
                  type="primary"
                  v-if="!readOnly"
                  @click="generateSKU()"
                  >生成SKU</el-button
                >
              </div>
              <div class="base_details_content_second">
                <el-table :data="skuData" border style="width: 100%">
                  <el-table-column
                    :label="attrFieldName"
                    prop="attrDetail"
                    align="center"
                    width="140"
                  />
                  <el-table-column
                    label="SKU编号"
                    prop="skuCode"
                    align="center"
                  />

                  <el-table-column label="SKU图片" align="center" width="120">
                    <template #default="scope">
                      <UploadSinglePicture
                        v-model="scope.row.skuPic"
                        :width="100"
                        :disabled="readOnly"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="库存"
                    prop="stockNum"
                    align="center"
                    width="100"
                  >
                    <template #default="scope">
                      <el-input
                        type="number"
                        v-model.number="scope.row.stockNum"
                        placeholder="请输入"
                        :disabled="readOnly"
                        onkeyup="value=value.replace(/^(0+)|[^\d]+/g,'')"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="成本价(元)"
                    align="center"
                    width="100"
                  >
                    <template #default="scope">
                      <el-input-number
                        v-model.number="scope.row.costPrice"
                        :min="0"
                        :precision="2"
                        :disabled="readOnly"
                        :controls="false"
                        controls-position="right"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="同行价(元)"
                    align="center"
                    width="100"
                  >
                    <template #default="scope">
                      <el-input-number
                        v-model.number="scope.row.competitorPrice"
                        :min="0"
                        :precision="2"
                        :disabled="readOnly"
                        :controls="false"
                        controls-position="right"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="销售价(元)"
                    align="center"
                    width="100"
                  >
                    <template #default="scope">
                      <el-input-number
                        v-model.number="scope.row.sellPrice"
                        :min="0"
                        :precision="2"
                        :disabled="readOnly"
                        :controls="false"
                        controls-position="right"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="划线价(元)"
                    align="center"
                    width="100"
                  >
                    <template #default="scope">
                      <el-input-number
                        v-model.number="scope.row.markingPrice"
                        :min="0"
                        :precision="2"
                        :disabled="readOnly"
                        :controls="false"
                        controls-position="right"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column label="状态" align="center" width="100">
                    <template #default="scope">
                      <el-switch
                        v-model="scope.row.flag"
                        active-text="启用"
                        inactive-text="禁用"
                        :active-value="1"
                        :inactive-value="0"
                        inline-prompt
                        size="large"
                        :disabled="readOnly"
                        @change="skuEnableStateChange($event, scope.$index)"
                      />
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-main>
      <el-footer>
        <el-button @click="route.go(-1)" v-show="activeName === 'basic'"
          >取消</el-button
        >
        <el-button
          @click="tabChange('spec')"
          v-show="activeName === 'basic'"
          type="primary"
          >下一步</el-button
        >
        <el-button @click="tabChange('basic')" v-show="activeName === 'spec'"
          >上一步</el-button
        >
        <el-button
          @click="save(false)"
          v-show="activeName === 'spec'"
          type="primary"
          v-if="!readOnly"
          >保存
        </el-button>
        <el-button
          @click="save(true)"
          v-show="activeName === 'spec'"
          type="primary"
          v-if="!readOnly"
          >保存并提交审核
        </el-button>
        <el-button
          @click="approvalPass"
          v-show="activeName === 'spec' && basicForm.flowStatus == '1007002'"
          type="primary"
          v-if="isApproval"
          >审批通过</el-button
        >
        <el-button
          @click="approvalRefusal"
          v-show="activeName === 'spec' && basicForm.flowStatus == '1007002'"
          type="primary"
          v-if="isApproval"
          >审批驳回</el-button
        >
      </el-footer>
    </el-container>
  </div>
</template>

<script setup>
import BackTitleView from "@com/BackTitleView.vue";
import GoodsSpecs from "@com/goods/GoodsSpecs.vue";
import UploadPicture from "@com/upload/UploadPicture.vue";
import DataCollectTable from "@com/table/DataCollectTable.vue";
import { ref, reactive } from "vue";
import $ from "@util/base";
import { $msg, $box } from "@/common/ui/msg";
import useRoute from "@util/router";
// import testSkuData from "@/test/skuData.json"
import UploadSinglePicture from "@com/upload/UploadSinglePicture.vue";
import goodsConfigApi from "@api/goodsConfig";
import api from "@api/goods";
const aaa = "value=value.replace('-', '')";

const attrFieldName = ref("");
const specsData = ref({
  skuSaleAttr1: null,
  skuSaleAttr2: null,
  skuSaleAttr1Value: [],
  skuSaleAttr2Value: [],
});
const skuData = ref([]);
const route = useRoute();
const activeName = ref("basic");
const deliverOptions = [
  {
    label: "快递",
    value: "1045002",
  },
  {
    label: "自提",
    value: "1045003",
  },
  {
    label: "快递和自提",
    value: "1045001",
  },
];

function clearNoNum(obj) {
  obj.value = obj.value.replace(/[^\d.]/g, ""); //清除“数字”和“.”以外的字符
  obj.value = obj.value.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的
  obj.value = obj.value
    .replace(".", "$#$")
    .replace(/\./g, "")
    .replace("$#$", ".");
  obj.value = obj.value.replace(/^(-)*(\d+)\.(\d\d).*$/, "$1$2.$3"); //只能输入两个小数
  if (obj.value.indexOf(".") < 0 && obj.value != "") {
    //以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
    obj.value = parseFloat(obj.value);
  }
}

function tabChange(active) {
  if (active == "spec") {
    basicFormRef.value.validate((valid, fields) => {
      if (valid && checkUnit()) {
        activeName.value = active;
      }
    });
  } else {
    activeName.value = active;
  }
}

const urlQuery = route.query();
var readOnly = false;
var isModify = false;
var isApproval = false;
var title = "邮费模板详情";
$.handleCRU(urlQuery.type, {
  show: () => {
    readOnly = true;
    title = "商品详情";
    getData();
  },
  add: () => {
    title = "新增商品";
  },
  modify: () => {
    title = "修改商品";
    isModify = true;
    getData();
  },
  examine: () => {
    readOnly = true;
    isApproval = true;
    title = "商品详情";
    getData();
  },
});

const typeOptions = ref([]);
// const baseOptions = ref([])
const postageOptions = ref([]);
const specsOptions = ref([]);
const labelOptions = ref([]);
const stationOptions = ref([]);

getConfig();
function getConfig() {
  goodsConfigApi.category((val) => {
    typeOptions.value = val;
  });
  // goodsConfigApi.base(val => { baseOptions.value = val })
  goodsConfigApi.express((val) => {
    postageOptions.value = val;
  });
  goodsConfigApi.goodsSpecs((val) => {
    specsOptions.value = val;
  });
  goodsConfigApi.label((val) => {
    labelOptions.value = val;
  });
  goodsConfigApi.station((val) => {
    stationOptions.value = val;
  });
}

const otherUnit = ref();
const unitOptions = ["个", "份", "箱", "其他"];

const goodsSpecs = ref(null);

const basicFormRef = ref(null);

const basicForm = reactive({
  id: null,
  productCode: null,
  categoryCode: null,
  productName: null,
  // shopCode: null,
  limitDeliveryType: null,
  sellUnit: null,
  postageTempleteCode: null,
  stationIds: [],
  tags: null,
  maxBuy: null,
  minBuy: 1,
  descList: [],
  picList: [],
  flowStatus: null,
  flowCode: null,
});

const basicRules = {
  categoryCode: [
    {
      required: true,
      message: "请选择商品分类",
      trigger: "change",
    },
  ],
  limitDeliveryType: [
    {
      required: true,
      message: "请选择发货方式",
      trigger: "blur",
    },
  ],
  productName: [
    {
      required: true,
      message: "请输入商品名称",
      trigger: "blur",
    },
  ],
  // shopCode: [{
  //   required: true,
  //   message: '请选择归属基地',
  //   trigger: 'change',
  // }],
  picList: [
    {
      required: true,
      type: "array",
      message: "请上传商品封面",
      trigger: "change",
    },
  ],
  descList: [
    {
      required: true,
      type: "array",
      message: "请上传商品简介",
      trigger: "change",
    },
  ],
  sellUnit: [
    {
      required: true,
      message: "请选择商品单位",
      trigger: "change",
    },
  ],
  postageTempleteCode: [
    {
      required: true,
      message: "请选择邮费模板",
      trigger: "change",
    },
  ],
  stationIds: [
    {
      required: true,
      type: "array",
      message: "请选择可选自提点",
      trigger: "change",
    },
  ],
  minBuy: [
    {
      required: true,
      message: "请输入起购数量",
      trigger: "blur",
    },
    {
      type: "number",
      min: 1,
      message: "起购数量最小值为1",
      trigger: "blur",
    },
  ],
};

function getData() {
  api.details(route.query().code, (val) => {
    basicForm.id = val.id;
    basicForm.categoryCode = val.categoryCode;
    basicForm.productName = val.productName;
    // basicForm.shopCode = val.shopCode
    basicForm.postageTempleteCode = val.postageTempleteCode;
    basicForm.limitDeliveryType = val.limitDeliveryType;
    basicForm.stationIds = val.stationIds;
    basicForm.tags = parseInt(val.tags);
    basicForm.maxBuy = val.maxBuy;
    basicForm.minBuy = val.minBuy;
    basicForm.descList = val.descList;
    basicForm.picList = val.picList;
    basicForm.flowStatus = val.flowStatus;
    basicForm.flowCode = val.flowCode;
    if (unitOptions.includes(val.sellUnit)) {
      basicForm.sellUnit = val.sellUnit;
    } else {
      basicForm.sellUnit = "其他";
      otherUnit.value = val.sellUnit;
    }

    let sku = val.sku;
    attrFieldName.value = sku.attrName;
    specsData.value = {
      skuSaleAttr1: sku.skuSaleAttr1,
      skuSaleAttr2: sku.skuSaleAttr2,
      skuSaleAttr1Value: sku.skuSaleAttr1Value,
      skuSaleAttr2Value: sku.skuSaleAttr2Value,
    };
    skuData.value = sku.itemList;
  });
}

function generateSKU() {
  basicFormRef.value.validate((valid, fields) => {
    if (valid && checkUnit()) {
      let specsData = goodsSpecs.value.getValue();
      if (specsData != false) {
        let goodsData = $.deepCopy(basicForm);
        if (goodsData.limitDeliveryType === "1045002") {
          goodsData.stationIds = [];
        } else if (goodsData.limitDeliveryType === "1045003") {
          goodsData.postageTempleteCode = null;
        }
        goodsData.sellUnit = getUnit();
        goodsData.specs = specsData;
        api.generateSKU(goodsData, (val) => {
          basicForm.productCode = val.productCode;
          attrFieldName.value = val.attrName;
          skuData.value = val.itemList;
        });
      }
    } else {
      $msg.error("请完善基本信息");
    }
  });
}
function getUnit() {
  if (basicForm.sellUnit != "其他") {
    return basicForm.sellUnit;
  } else {
    return otherUnit.value;
  }
}
function checkUnit() {
  if (basicForm.sellUnit == "其他" && $.isEmpty(otherUnit.value)) {
    $msg.error("请输入单位");
    return false;
  }
  return true;
}

function checkSKU() {
  if ($.isEmpty(skuData.value)) {
    $msg.error("请生成SKU");
    return false;
  }
  for (const item of skuData.value) {
    //1 有效、 0 无效
    if (item.flag == 1) {
      for (const key in item) {
        if ($.isEmpty(item[key])) {
          $msg.error("请完善SKU数据");
          return false;
        }
      }
    }
  }
  return true;
}

function save(isExamine) {
  basicFormRef.value.validate((valid, fields) => {
    if (valid && checkUnit()) {
      if (checkSKU()) {
        $.handleCRU(route.query().type, {
          add: () => {
            skuSubmit(isExamine);
          },
          modify: () => {
            updateSKUSubmit(isExamine);
          },
        });
      }
    } else {
      $msg.error("请完善基本信息");
    }
  });
}

function skuSubmit(isExamine) {
  api.skuSubmit(
    {
      productCode: basicForm.productCode,
      // shopCode: basicForm.shopCode,
      itemList: skuData.value,
      isExamine: isExamine,
    },
    () => {
      $msg.succ("保存成功");
      route.go(-1);
    }
  );
}

function updateSKUSubmit(isExamine) {
  basicFormRef.value.validate((valid, fields) => {
    if (valid && checkUnit()) {
      let goodsData = $.deepCopy(basicForm);
      if (goodsData.limitDeliveryType === "1045002") {
        goodsData.stationIds = [];
      } else if (goodsData.limitDeliveryType === "1045003") {
        goodsData.postageTempleteCode = null;
      }
      goodsData.sellUnit = getUnit();
      goodsData.sku = {
        productCode: basicForm.productCode,
        // shopCode: basicForm.shopCode,
        itemList: skuData.value,
        isExamine: isExamine,
      };
      api.updateSKUSubmit(goodsData, () => {
        $msg.succ("修改成功");
        route.go(-1);
      });
    } else {
      $msg.error("请完善基本信息");
    }
  });
}

function skuEnableStateChange(evt, index) {
  let data = skuData.value[index];
  if ($.isNotEmpty(data.skuCode)) {
    // 1 有效、 0 无效
    if (evt == 1) {
      for (const key in data) {
        if ($.isEmpty(data[key])) {
          $msg.error("请完善SKU数据");
          data.flag = 0;
          return;
        }
      }
    }
    api.skuFlagUpdata(
      data.skuCode,
      evt,
      () => {
        $msg.succ("操作成功");
      },
      () => {
        data.flag = evt == 1 ? 0 : 1;
      }
    );
  }
}

// 审批通过
function approvalPass() {
  $box.open("通过", "确认该商品审批通过", () => {
    api.approval(basicForm.flowCode, "1007004", "", () => {
      $msg.succ("审批成功");
      route.go(-1);
    });
  });
}

// 驳回
function approvalRefusal() {
  $box.input("确认驳回", "驳回原因", null, (val) => {
    api.approval(basicForm.flowCode, "1007003", val, () => {
      $msg.succ("驳回成功");
      route.go(-1);
    });
  });
}
</script>

<style lang="scss" scoped>
.goods_details {
  height: 100%;
}

::v-deep input::-webkit-outer-spin-button,
::v-deep input::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
}

::v-deep input[type="number"] {
  -moz-appearance: textfield !important;
}

.unit_input {
  width: 88px !important;
  margin-left: 8px !important;
}
</style>
